package api

import (
	"github.com/gin-gonic/gin"
	"server/global"
	"server/internal/middleware"
	model2 "server/internal/model"
	"server/internal/pkg/response"
	"server/internal/services"
)

// TissueApi 组织管理
var TissueApi = new(tissueApi)

type tissueApi struct {
	model2.Tissue
}

// Router 路由
func (a tissueApi) Router(r *gin.RouterGroup) {
	api := r.Group("/tissue", middleware.LoginVerification, middleware.PermissionVerification)
	//验证权限
	api.GET("/list", a.list)
	api.GET("/stat_list", a.statList)
	api.GET("/edit", a.detail)
	api.POST("/add", a.add)
	api.POST("/edit", a.edit)
	api.POST("/del", a.del)

	api2 := r.Group("/tissue", middleware.LoginVerification)
	api2.GET("/get_select", a.getSelect)
}

// List 列表
func (a tissueApi) list(c *gin.Context) {

	response.SuccessList(c, services.Tissue.GetList(0), 0)
}

// Detail 单条
func (a tissueApi) detail(c *gin.Context) {
	id := c.Query("id")

	detail := services.Tissue.GetById(id)

	response.SuccessData(c, detail, "")
}

// Add 添加
func (a tissueApi) add(c *gin.Context) {

	if err := c.ShouldBindJSON(&a); err != nil {
		response.Error(c, "参数错误", err.Error())
		return
	}

	if _, err := services.Tissue.Create(a.Tissue); err == nil {
		response.Success(c, "", "添加成功")
	} else {
		response.Error(c, "添加失败", err.Error())
	}
}

// Edit 编辑
func (a tissueApi) edit(c *gin.Context) {

	if err := c.ShouldBindJSON(&a); err != nil {
		response.Error(c, "参数错误", err.Error())
		return
	}

	if _, err := services.Tissue.Update(a.Tissue); err == nil {
		response.Success(c, "", "编辑成功")
	} else {
		response.Error(c, "编辑失败")
	}
}

// Del 删除
func (a tissueApi) del(c *gin.Context) {
	type Param struct {
		Ids []int `json:"ids"`
	}
	var param Param
	if err := c.ShouldBindJSON(&param); err != nil {
		response.Error(c, "参数错误", err.Error())
		return
	}
	if services.Tissue.Delete(param.Ids) == nil {
		response.Success(c, "", "删除成功")
	} else {
		response.Error(c, "删除失败")
	}
}

// GetSelect 远程下啦
func (a tissueApi) getSelect(c *gin.Context) {

	rules, _ := c.Get("rules")
	rulesString := rules.(string)

	userInfo, _ := c.Get("userInfo")

	if rulesString == "*" {
		response.Success(c, services.Tissue.Select(0), "")
	} else {

		response.Success(c, services.Tissue.Selects(userInfo.(model2.User).TissueId), "")
	}

}

// StatList 带统计的列表
func (a tissueApi) statList(c *gin.Context) {
	Db := global.GL_DB          //初始化Db
	Db = services.Paging(Db, c) //分页
	pid := c.Query("pid")
	rules, _ := c.Get("rules")
	rulesString := rules.(string)

	userInfo, _ := c.Get("userInfo")

	if pid == "" {
		if rulesString == "*" {
			Db = Db.Where("pid = ?", 0)
		} else {
			Db = Db.Where("id = ?", userInfo.(model2.User).TissueId)
		}

	} else {
		Db = Db.Where("pid = ?", pid)
	}

	_, list, total := services.Tissue.StatList(Db)

	response.SuccessList(c, list, total)
}
